package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.comm.bean.WordDoc;
import com.uinnova.product.eam.service.IEamWordSvc;
import com.uinnova.product.eam.service.es.IamsESWordDocEsDao;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.query.CSysUser;
import com.uino.dao.util.ESUtil;
import com.uino.service.sys.microservice.IResourceSvc;
import com.uino.util.rsm.RsmUtils;
import com.uino.util.sys.SysUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * 文档管理服务层实现
 *
 * @author lichong
 */
@Deprecated
@Service
public class IamsWordSvcImpl implements IEamWordSvc {

    private static final Logger log = LoggerFactory.getLogger(IamsWordSvcImpl.class);

    @Value("${local.resource.space}")
    private String localPath;

    @Value("${http.resource.space}")
    private String urlPath;

    @Autowired
    private IResourceSvc resourceSvc;

    @Autowired
    private IamsESWordDocEsDao wordDocEsDao;

    @Autowired
    private IUserApiSvc userApiSvc;

    @Autowired
    private RsmUtils rsmUtils;

    /**
     * 文档合法性正则
     */
    @Value("${uino.eam.word_name_regex}")
    private String wordNameregex;

    @Override
    public WordDoc uploadWord(String ciCode, MultipartFile wordFile) {
        BinaryUtils.checkEmpty(ciCode, "ciCode");
        boolean flag = true;
        Long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath + "/" + dateTimeFolder);
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }
        String docName = wordFile.getOriginalFilename().substring(0, wordFile.getOriginalFilename().lastIndexOf("."));
        String fileType = wordFile.getOriginalFilename().substring(wordFile.getOriginalFilename().lastIndexOf(".") + 1);
        if (!(wordFile.getOriginalFilename().matches(wordNameregex))) {
            return null;
        }
        // 重复替换，暂时去掉
//        List<WordDoc> words = wordDocEsDao
//                .getListByQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("ciCode.keyword", ciCode))
//                        .must(QueryBuilders.termQuery("docName.keyword", docName))
//                        .must(QueryBuilders.termQuery("docType.keyword", fileType)));
//        if (!BinaryUtils.isEmpty(words)) {
//            return this.replaceWord(words.get(0).getId(), wordFile);
//        }
        String destFileName = ESUtil.getUUID() + "." + fileType;
        File destFile = new File(destFolder, destFileName);
        String realpath = null;
        try {
            String wordPath = "/" + dateTimeFolder + "/" + destFileName;
            realpath = destFile.getCanonicalPath();
            wordFile.transferTo(new File(destFile.getCanonicalPath()));
            realpath = destFile.getCanonicalPath();

            File realFile = new File(realpath);
            rsmUtils.uploadRsmFromFile(realFile);

            // 记录资源操作信息
            resourceSvc.saveSyncResourceInfo(wordPath, urlPath + wordPath, false, 0);
        } catch (IOException e) {
            flag = false;
            log.error("保存文件异常", e);
        }
        //在es中存储word信息
        WordDoc wordDoc = new WordDoc();
        wordDoc.setId(ESUtil.getUUID());
        wordDoc.setCiCode(ciCode);
        wordDoc.setDocName(docName);
        wordDoc.setDocType(fileType);
        wordDoc.setSavePth(realpath);
        wordDoc.setUpdateTime(LocalDateTime.now());
        wordDoc.setOperator(SysUtil.getCurrentUserInfo().getLoginCode());
        wordDoc.setFullPath("/"+dateTimeFolder+"/"+destFileName);
        wordDocEsDao.saveOrUpdate(wordDoc);
        String fullPath = urlPath+wordDoc.getFullPath();
        wordDoc.setFullPath(fullPath);
        return wordDoc;
    }

    @Override
    public boolean replaceWord(Long id, MultipartFile wordFile) {
        WordDoc wordDoc = wordDocEsDao.getById(id);
        //删除旧文件
        new File(wordDoc.getSavePth()).delete();
        rsmUtils.deleteRsm(wordDoc.getSavePth());

        boolean flag = true;
        long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath + "/" + dateTimeFolder);
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }
        String fileType = wordFile.getOriginalFilename().substring(wordFile.getOriginalFilename().lastIndexOf(".") + 1);
        if (!(wordFile.getOriginalFilename().matches(wordNameregex))) {
            return false;
        }
        String destFileName = ESUtil.getUUID() + "." + fileType;
        File destFile = new File(destFolder, destFileName);
        String realpath = null;
        String wordPath = "/" + dateTimeFolder + "/" + destFileName;
        try {
            wordFile.transferTo(new File(destFile.getCanonicalPath()));
            realpath = destFile.getCanonicalPath();
            File realFile = new File(realpath);
            rsmUtils.uploadRsmFromFile(realFile);
            resourceSvc.saveSyncResourceInfo(wordPath, urlPath + wordPath, false, 2);
        } catch (IOException e) {
            flag = false;
            log.error("word文件创建失败", e);
        }
        wordDoc.setSavePth(realpath);
        wordDoc.setUpdateTime(LocalDateTime.now());
        wordDoc.setOperator(SysUtil.getCurrentUserInfo().getLoginCode());
        wordDocEsDao.saveOrUpdate(wordDoc);
        return flag;
    }

    @Override
    public boolean deleteWord(long id) {
        WordDoc wordDoc = getById(id);
        new File(wordDoc.getSavePth()).delete();
        resourceSvc.saveSyncResourceInfo(wordDoc.getSavePth(), wordDoc.getSavePth(), false, 1);
        return wordDocEsDao.deleteById(id) == 1;
    }

    @Override
    public WordDoc getById(Long id) {
        return wordDocEsDao.getById(id);
    }

    @Override
    public Page<WordDoc> getByCiCode(String ciCode, int pageNum, int pageSize) {
        WordDoc wordDoc = new WordDoc();
        wordDoc.setCiCode(ciCode);
        Page<WordDoc> listByCdt = wordDocEsDao.getSortListByCdt(pageNum, pageSize, wordDoc, "modifyTime", false);
        HashSet<String> loginCodeList = new HashSet<>();
        for (WordDoc datum : listByCdt.getData()) {
            loginCodeList.add(datum.getOperator());
        }
        HashMap<String, String> convertMap = new HashMap<>();
        List<SysUser> sysUserByCdt = null;
        String[] loginCodeArr = loginCodeList.toArray(new String[0]);
        if (loginCodeArr.length > 0) {
            CSysUser cSysUser = new CSysUser();
            cSysUser.setLoginCodes(loginCodeArr);
            sysUserByCdt = userApiSvc.getSysUserByCdt(cSysUser);
            if (!CollectionUtils.isEmpty(sysUserByCdt)) {
                for (SysUser sysUser : sysUserByCdt) {
                    convertMap.put(sysUser.getLoginCode(), sysUser.getUserName());
                }
            }
        }
        for(WordDoc s : listByCdt.getData()) {
            String savePth = s.getSavePth();
            s.setDocType(savePth.substring(savePth.lastIndexOf('.') + 1));
            s.setSavePth(null);
            String fullPath = s.getFullPath();
            s.setFullPath(urlPath+fullPath);
            if (CollectionUtils.isNotEmpty(sysUserByCdt)) {
                //将es存的loginCode转成用户名
                s.setOperator(convertMap.get(s.getOperator()));
            }
        }
        return listByCdt;
    }

    @Override
    public boolean wordDocIsExist(String ciCode, String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return false;
        }
        String docType = fileName.substring(fileName.lastIndexOf('.') + 1);
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("ciCode.keyword", ciCode))
                .must(QueryBuilders.termQuery("docName.keyword", fileName))
                .must(QueryBuilders.termQuery("docType.keyword", docType));
        return wordDocEsDao.existByCondition(queryBuilder);
    }
}
